package com.app.manage.moudles.push.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.app.manage.moudles.push.constants.TaskStepEnums;
import com.app.manage.moudles.push.dao.TCornTaskDao;
import com.app.manage.moudles.push.dao.TPushTaskDao;
import com.app.manage.moudles.push.entity.TCornTask;
import com.app.manage.moudles.push.entity.TPushTask;
import com.app.manage.moudles.push.pojo.TimeTaskPojo;
import com.app.manage.moudles.push.service.TCornTaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;

@Service
@Slf4j
public class TCornTaskServiceImpl implements TCornTaskService {

    private Map<Integer, TimeTaskPojo> runTaskMap = new HashMap<>();

    @Resource
    private TCornTaskDao cornTaskDao;

    @Resource
    private TPushTaskDao tPushTaskDao;

    @Override
    public void stopTask(Integer taskId) {
        TimeTaskPojo timeTask = runTaskMap.get(taskId);
        if(timeTask != null){
            Timer timer = timeTask.getTimer();
            timer.cancel();
            runTaskMap.remove(taskId);
            //从数据库中删除
            cornTaskDao.delete(new LambdaQueryWrapper<TCornTask>().eq(TCornTask::getTaskId,taskId));
        }
    }

    @Override
    public void addTask(Integer taskId, Date runDate, Function<Integer,String> f ,Boolean isAdd) {
        log.info("新增一个延迟任务：{} 执行时间：{}",taskId, DateUtil.format(runDate,"yyyy-MM-dd HH:mm:ss"));
        stopTask(taskId);

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                f.apply(taskId);
            }
        };
        timer.schedule(task,runDate);
        runTaskMap.put(taskId,new TimeTaskPojo(timer,taskId,runDate));
        if(isAdd){
            cornTaskDao.insert(new TCornTask(null,taskId,runDate));
        }
    }

    @Override
    public void checkTask() {
        List<TCornTask>  gqTaskList = cornTaskDao.selectList(
                new LambdaQueryWrapper<TCornTask>()
                .lt(TCornTask::getRunDate,new Date())
        );
        if(CollectionUtil.isEmpty(gqTaskList)){
            return;
        }

        //
        for(TCornTask cornTask : gqTaskList){
            TPushTask pushTask = tPushTaskDao.selectById(cornTask.getTaskId());
            if(pushTask != null){
                pushTask.setPushStep(TaskStepEnums.step_gq.getStep());
                pushTask.setPushRes("任务过期");
                tPushTaskDao.updateById(pushTask);
                cornTaskDao.deleteById(cornTask.getId());
            }
        }


    }
}
